package top.datacluster.basic.algorithm.leetcode.tree;

import top.datacluster.basic.algorithm.leetcode.TreeNode;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Stack;

public class LeetCode1571 {

    public List<List<Integer>> levelOrder(TreeNode root) {
        if (root == null){
            return new ArrayList<>();
        }
        List<List<Integer>> reslut = new ArrayList<>();
        List<Integer> temp = new ArrayList<>();
        Stack<TreeNode> odd = new Stack<>();
        Stack<TreeNode> even = new Stack<>();
        odd.push(root);
        while (odd.size() > 0 || even.size() > 0){
            if (odd.size() > 0){
                while (!odd.isEmpty()){
                    if (odd.peek().left != null)
                        even.push(odd.peek().left);
                    if (odd.peek().right != null)
                        even.push(odd.peek().right);
                    temp.add(odd.peek().val);
                    odd.pop();
                }

            }else{
                while (!even.isEmpty()){
                    if (even.peek().right != null)
                        odd.push(even.peek().right);
                    if (even.peek().left != null)
                        odd.push(even.peek().left);
                    temp.add(even.peek().val);
                    even.pop();
                }
            }
            reslut.add(temp);
            temp = new ArrayList<>();

        }
        return reslut;
    }

    public static void main(String[] args) {
        TreeNode node = new TreeNode(3);
        TreeNode node1 = new TreeNode(9);
        TreeNode node2 = new TreeNode(20);
        TreeNode node3 = new TreeNode(15);
        TreeNode node4 = new TreeNode(7);
        node.left = node1;
        node.right = node2;
        node2.left = node3;
        node2.right = node4;
        new LeetCode1571().levelOrder(node);
    }


}





